package com.tianji.login.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import javax.annotation.Resource;
/**
 * @Author jia
 * @Description 配置类用于定义客户端认证、令牌的生成及存储。
 * @Date 14:59 2024-10-04
**/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {

 @Resource(name = "authorizationServerTokenServicesCustom")
 private AuthorizationServerTokenServices authorizationServerTokenServices;

 @Autowired
 private AuthenticationManager authenticationManager;

 @Override
 public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  clients.inMemory() // 使用in-memory存储
          .withClient("XcWebApp") // client_id
          .secret(new BCryptPasswordEncoder().encode("XcWebApp")) // 客户端密钥
          .resourceIds("xuecheng-plus", "tianji") // 资源 ID 列表
          .authorizedGrantTypes("authorization_code", "password", "client_credentials", "implicit", "refresh_token") // 授权类型
          .scopes("all") // 授权范围
          .autoApprove(false) // 是否自动授权
          .redirectUris("http://www.51xuecheng.cn"); // 客户端接收授权码的重定向地址
 }

 @Override
 public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
  endpoints.authenticationManager(authenticationManager)
          .tokenServices(authorizationServerTokenServices)
          .allowedTokenEndpointRequestMethods(HttpMethod.POST);
 }

 @Override
 public void configure(AuthorizationServerSecurityConfigurer security) {
  security.tokenKeyAccess("permitAll()") // /oauth/token_key 公开
          .checkTokenAccess("permitAll()") // /oauth/check_token 公开
          .allowFormAuthenticationForClients(); // 允许表单认证（申请令牌）
 }
}
